package org.example.springboot.controller;

import org.example.springboot.common.Result;
import org.example.springboot.entity.News;
import org.example.springboot.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @GetMapping("/page")
    public Result getNewsByPage(@RequestParam(defaultValue = "1") int pageNum,
                                @RequestParam(defaultValue = "5") int pageSize,
                                @RequestParam(required = false) String title) {
        int total = newsService.getNewsCount(title);
        List<News> list = newsService.getNewsByPage(pageSize, pageNum, title);

        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("list", list);

        return Result.success(result);
    }

    @PostMapping("/add")
    public Result addNews(@RequestBody News news) {
        newsService.insertNews(news);
        return Result.success("新增新闻成功");
    }

    @PostMapping("/update")
    public Result updateNews(@RequestBody News news) {
        newsService.updateNews(news);
        return Result.success("更新新闻成功");
    }

    @DeleteMapping("/del/{id}")
    public Result deleteNews(@PathVariable int id) {
        newsService.deleteNewsById(id);
        return Result.success("删除新闻成功");
    }

    @GetMapping("/selectAll")
    public Result selectAllNews() {
        return Result.success(newsService.getAllNews());
    }

    @PostMapping("/selectById/{id}")
    public Result selectById(@PathVariable int id) {
        return Result.success(newsService.getNewsById(id));
    }
}
